package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.consts.SerialKeys;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.InspectionEquipment;
import com.scs.application.modules.base.mapper.InspectionEquipmentMapper;
import com.scs.application.modules.base.service.InspectionEquipmentService;
import com.scs.application.core.service.BaseServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 检验设备 服务实现类
 * </p>
 */
@Service
public class InspectionEquipmentServiceImpl extends BaseServiceImpl<InspectionEquipmentMapper, InspectionEquipment> implements InspectionEquipmentService {

    @Override
    public boolean saveOrUpdate(InspectionEquipment entity) {
        if (entity.isNewRecord()) {
            if (checkName(entity.getName())) {
                throw new BusinessException("已存在相同的检验设备名称，请重新输入");
            }
            entity.setCode(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.BASE_INSPECTION_EQUIPMENT_CODE));
            entity.setSn(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.WM_STOCK_PROCESS_SN));
        } else {
            if (!getById(entity.getId()).getName().equals(entity.getName()) && checkName(entity.getName())) {
                throw new BusinessException("已存在相同的检验设备名称，请重新输入");
            }
            if (StringUtils.isEmpty(entity.getSn())) {
                entity.setSn(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.WM_STOCK_PROCESS_SN));
            }
        }
        return super.saveOrUpdate(entity);
    }

    /**
     * 校验检验设备名称是否重复
     */
    private boolean checkName(String name) {
        return getOne(new QueryWrapper<InspectionEquipment>().eq("name", name)) != null;
    }

}
